package com.itshizhan.viewmodeldemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    //private val numberPlusViewModel by viewModels<NumberPlusViewModel>();
    //lateinit var numberPlusViewModel:NumberPlusViewModel
    lateinit var numberPlusViewModelWithArg: NumberPlusViewModelWithArg

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //'ViewModelProviders' is deprecated. Deprecated in Java
        //numberPlusViewModel = ViewModelProviders.of(this).get(NumberPlusViewModel::class.java)
        //lifecycle-extensions 中的 API 已弃用。
        //弃用 ViewModelProviders.of()：已弃用 ViewModelProviders.of()。
        //您可以将 Fragment 或 FragmentActivity 传递给新的 ViewModelProvider(ViewModelStoreOwner) 构造函数，以便在使用 Fragment 1.2.0 时实现相同的功能。
        //numberPlusViewModel = ViewModelProvider(this)[NumberPlusViewModel::class.java]
        //numberPlusViewModel = CreateVM().create(NumberPlusViewModel::class.java)  // 每次都会重建

        //        tv.text = numberPlusViewModel.number.toString()
        //        btn1.setOnClickListener {
        //            numberPlusViewModel.number++
        //            tv.text = numberPlusViewModel.number.toString()
        //        }

        numberPlusViewModelWithArg = ViewModelProvider(this,MyViewModelFactory(10))[NumberPlusViewModelWithArg::class.java]
        tv.text = numberPlusViewModelWithArg.number.toString()
        btn1.setOnClickListener {
            numberPlusViewModelWithArg.number++
            tv.text = numberPlusViewModelWithArg.number.toString()
        }

    }

}